//
//  BSOauthViewController.swift
//  mySwiftWeibo
//
//  Created by apple on 16/7/19.
//  Copyright © 2016年 itcast沈庆伟. All rights reserved.
//

import UIKit
import SVProgressHUD


class BSOauthViewController: UIViewController {

    //添加webview
    override func loadView() {
        self.view=webView
        
        //代理
        webView.delegate=self
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //背景颜色
        self.view.backgroundColor=UIColor.whiteColor()
        
        //设置导航栏
        setNavi()
        
        //使用webview加载登录界面
        //GET,在地址后面:?参数1=值&参数2=值&参数3=值
        //https://api.weibo.com/oauth2/authorize?client_id=1321823220&redirect_uri=http://www.baidu.com
        let urlString="https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        let urlRequest=NSURLRequest(URL: NSURL(string: urlString)!)
        webView.loadRequest(urlRequest)
        
        //显示加载
        SVProgressHUD.setMinimumDismissTimeInterval(2)
        //SVProgressHUD.showErrorWithStatus("正在加载...")  //显示出错,2秒后自动关闭
        //进度一直转,只有dismiss才会关闭
        SVProgressHUD.showWithStatus("正在加载...")
    }
    
    ///设置导航栏
    private func setNavi(){
        self.title="登录"
        self.navigationItem.leftBarButtonItem=UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        self.navigationItem.rightBarButtonItem=UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }

    //MARK: - 按钮绑定事件
    //自动填充账号和密码
    func autoFill(){
        //print("autoFill")
        //let jsCode="document.getElementById('userId').value='czbkiosweibo@163.com';document.getElementById('passwd').value='czbkios111'"
        let jsCode="document.getElementById('userId').value='qingwei.qw@163.com';document.getElementById('passwd').value='S-Q-W-537297'"
        //使用webview执行js代码(js与oc交互)
        webView.stringByEvaluatingJavaScriptFromString(jsCode)
    }
    func close(){
        //print("close")
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    //MARK: - 懒加载
    private lazy var webView=UIWebView()
   
}

//MARK: - webview代理方法
extension BSOauthViewController:UIWebViewDelegate{
    
    ///webview加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //每当webview要去加载一个网页时都会调用这个方法,询问我们是否真的要去加载,返回:false就不加载,返回true就去加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //Optional("http://www.baidu.com/?code=dfe25856274685c0b376a0721af95432")
        //强拆包
        let urlString=request.URL!.absoluteString
        print("加载的地址: \(urlString)")
        
        //其他界面不需要拦截,只需要拦截授权回调的地址
        if !urlString.hasPrefix(redirect_uri){
            //不是授权回调地址,放过去,让webView去加载
            return true
        }else{
            //是授权回调地址
            //取消授权:"https://m.baidu.com/?error_uri=%2Foauth2%2Fauthorize......
            //授权:http://www.baidu.com/?code=dfe25856274685c0b376a0721af95432
            
            //?后面的东西叫query
            //区分 取消授权 和 授权按钮,看?后面是否是以code=开头
            let query=request.URL!.query!
            print("query: \(query)")
            //判断query是否以code=开头
            let codeString="code="
            if query.hasPrefix(codeString){
                //点击了授权
                print("点击了授权")
                //截取code=后面的字符串
                let nsQuery=query as NSString
                let code=nsQuery.substringFromIndex(codeString.characters.count)
                //print("截取的code= \(code)")
                
                //post请求加载OAuth2的access_token
                //loadAccess_Token(code)
                BSUserAccountViewModel.sharedUserAccountViewModel.loadAccessToken(code, completion: { (error) -> Void in
                    //网络失败也调用
                    if error != nil {
                        SVProgressHUD.showErrorWithStatus("加载AccessToken出错了")
                        
                        //延迟关闭
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), {() -> Void in
                            SVProgressHUD.dismiss()
                            self.close()
                        })
                        return
                    }
                    
                    //保存账号后会调用
                    //关闭控制器
                    self.close()
                    AppDelegate.switchRootViewController(BSWelcomeViewController())
                })
                
            }else{
                //点击了取消
                self.close()
            }
             return false
        }
    }
    
//    //获取授权access_token令牌
//    private func loadAccess_Token(code:String){
//        //URL:https://api.weibo.com/oauth2/access_token
//        let URLString="https://api.weibo.com/oauth2/access_token"
//        let parameter=[
//            "client_id":client_id,
//            "client_secret":app_secret,
//            "grant_type":"authorization_code",
//            "code":code,
//            "redirect_uri":redirect_uri
//        ]
//        
//        //post请求
//        BSNetWorkTool.sharedNetworkTool.POST(URLString, parameters: parameter, progress: nil, success: { (_, responseObject) -> Void in
//            //print("responseObject: \(responseObject)")
//            /*
//            "access_token" = "2.00YJnIMG3bO98Babd589ef208zw2_B";
//            "expires_in" = 152208;
//            "remind_in" = 152208;
//            uid = 5676208596;
//            */
//            //字典转模型-先转字典
//            let dict = responseObject as! [String: AnyObject]
//            let userAccount = BSUserAccount(dict: dict)
//            
//            print("userAccount = \(userAccount)")
//            }) { (_, error) -> Void in
//                
//                print("error: \(error)")
//        }
//    }
}
